﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using VIP.Data.EFProvider;
using VIP.Data.Entities;
using VIP.Domain.Core.DomainObject;
using VIP.Domain.Core.Factories;
using VIP.Domain.DTO;
using VIP.Domain.VO;
using VIP.Events;

namespace VIP.Domain.BusServices.Impl
{
    public class OrderService : IOrderService
    {
        private readonly IAggregateRootLoader<OrderObj> _loader;
        private readonly IEventSender _eventSender;
        private readonly IUnitOfWork<VIPDbContext> _unitOfWork;
        private readonly IMapper _mapper;

        public OrderService(IAggregateRootLoader<OrderObj> ordersLoader, IUnitOfWork<VIPDbContext> unitOfWork, IEventSender eventSender, IMapper mapper)
        {
            _loader = ordersLoader;
            _eventSender = eventSender;
            _mapper = mapper;
            _unitOfWork = unitOfWork;
        }
        public async Task<Guid> AddItem(Guid orderId, OrderItemDTO dto)
        {
            var orderObj = await _loader.LoadAsync(orderId);
            orderObj.AddItem(orderId, dto);

            foreach (var @event in orderObj.Events)
            {
                await _eventSender.SendAsync(@event);
            }

            return await Task.Run(() =>
            {
                return Guid.NewGuid();
            });
        }

        public Task<OrderVO> Create(CreateOrderDTO dto)
        {
            var order = new OrderObj();
            //创建订单
            order.Create(dto);
            //todo 这里可能涉及多个聚合根，可以做成事务
            foreach (var @event in order.Events)
            {
                _eventSender.SendAsync(@event);
            }

            return Task.Run(() =>
            {
                return new OrderVO()
                {
                    Code = dto.code
                };
            });
        }

        public async Task<OrderVO> Query(string orderCode)
        {
            var rep = _unitOfWork.GetRepositoryAsync<Order>();
            var entity = await rep.SingleAsync(p => p.Code == orderCode);
            return _mapper.Map<OrderVO>(entity);
        }

        public Task<bool> UpdateCustomName(Guid id, string name)
        {
            throw new Exception();
        }
    }
}
